package com.pwp.activity;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TimePicker;

import com.agent.crm.base.BaseActivity;
import com.agent.crm.db.DBInitScript;
import com.agent.crm.db.DatabaseManager;
import com.agent.crm.view.R;
import com.pwp.borderText.BorderTextView;
import com.pwp.calendar.LunarCalendar;
import com.pwp.constant.CalendarConstant;
import com.pwp.dao.ScheduleDAO;
import com.pwp.vo.ScheduleDateTag;
import com.pwp.vo.ScheduleVO;

/**
 * 添加日程主界面
 * 
 * @author jack_peng
 * 
 */
public class ScheduleView extends BaseActivity {

	private LunarCalendar lc = null;
	private ScheduleDAO dao = null;
	private BorderTextView scheduleType = null;
	private BorderTextView dateText = null;
	private BorderTextView endDateText = null;
	private BorderTextView scheduleTop = null;
	private BorderTextView scheduleObject = null;
	private EditText scheduleTitle = null;
	private EditText scheduleText = null;
	private BorderTextView scheduleSave = null; // 保存按钮图片
	private static int hour = -1;
	private static int minute = -1;
	private String[] scheduleDate = new String[4];
	private String[] scheduleEndDate = new String[4];

	private String scheduleStartDateTxt = "";
	private String scheduleEndDateTxt = "";
	private ArrayList<ScheduleDateTag> dateTagList = new ArrayList<ScheduleDateTag>();
	private String scheduleYear = "";
	private String scheduleMonth = "";
	private String scheduleDay = "";
	private String week = "";
	private String selectMode;
	boolean time_picker_flag = false;
	String selectObjectId = "";
	ArrayList<String> list_object = new ArrayList<String>();
	List<String[]> datas = new ArrayList<String[]>();

	ListAdapter adapter;

	// 临时日期时间变量，
	private String tempMonth;
	private String tempDay;

	private String[] sch_type = CalendarConstant.sch_type;
	private String[] remind = CalendarConstant.remind;
	private int sch_typeID = 0; // 日程类型
	private int remindID = 0; // 提醒类型
	ProgressDialog pDialog;
	String operateType = null;

	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			Bundle bundle = msg.getData();
			if (null == bundle) {
				return;
			}
			if ("saveFinish".endsWith(bundle.getString("msg"))) {
				if (null != pDialog && pDialog.isShowing()) {
					pDialog.dismiss();
					finish();
				}

			}
		}

	};

	private static String schText = "";

	// int schTypeID = 0;

	public ScheduleView() {
		lc = new LunarCalendar();
		dao = new ScheduleDAO(this);
	}

	/**
	 * 设置日程标记日期
	 * 
	 * @param remindID
	 * @param year
	 * @param month
	 * @param day
	 */
	public void setScheduleDateTag(int remindID, String year, String month,
			String day, int scheduleID) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-M-d");
		String d = year + "-" + month + "-" + day;
		Calendar cal = Calendar.getInstance();
		try {
			cal.setTime(format.parse(d));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 封装要标记的日期
		if (remindID >= 0 && remindID <= 3) {
			// "提醒一次","隔10分钟","隔30分钟","隔一小时"（只需标记当前这一天）
			ScheduleDateTag dateTag = new ScheduleDateTag();
			dateTag.setYear(Integer.parseInt(year));
			dateTag.setMonth(Integer.parseInt(month));
			dateTag.setDay(Integer.parseInt(day));
			dateTag.setScheduleID(scheduleID);
			dateTagList.add(dateTag);
		} else if (remindID == 4) {
			// 每天重复(从设置的日程的开始的之后每一天多要标记)
			Calendar start = Calendar.getInstance();
			start.set(Integer.valueOf(scheduleDate[0]),
					Integer.valueOf(scheduleDate[1]),
					Integer.valueOf(scheduleDate[2]));
			Calendar end = Calendar.getInstance();
			end.set(Integer.valueOf(scheduleEndDate[0]),
					Integer.valueOf(scheduleEndDate[1]),
					Integer.valueOf(scheduleEndDate[2]));
			for (int i = 0; i <= ((end.getTimeInMillis() - start
					.getTimeInMillis()) / (24 * 60 * 60 * 1000)); i++) {
				if (i == 0) {
					cal.add(Calendar.DATE, 0);
				} else {
					cal.add(Calendar.DATE, 1);
				}
				handleDate(cal, scheduleID);
			}
		} else if (remindID == 5) {
			// 每周重复(从设置日程的这天(星期几)，接下来的每周的这一天多要标记)
			Calendar start = Calendar.getInstance();
			start.set(Integer.valueOf(scheduleDate[0]),
					Integer.valueOf(scheduleDate[1]),
					Integer.valueOf(scheduleDate[2]));
			Calendar end = Calendar.getInstance();
			end.set(Integer.valueOf(scheduleEndDate[0]),
					Integer.valueOf(scheduleEndDate[1]),
					Integer.valueOf(scheduleEndDate[2]));
			for (int i = 0; i <= (end.getTimeInMillis() - start
					.getTimeInMillis()) / (7 * 24 * 60 * 60 * 1000); i++) {
				if (i == 0) {
					cal.add(Calendar.WEEK_OF_MONTH, 0);
				} else {
					cal.add(Calendar.WEEK_OF_MONTH, 1);
				}
				handleDate(cal, scheduleID);
			}
		} else if (remindID == 6) {
			// 每月重复(从设置日程的这天(几月几号)，接下来的每月的这一天多要标记)
			Calendar start = Calendar.getInstance();
			start.set(Integer.valueOf(scheduleDate[0]),
					Integer.valueOf(scheduleDate[1]),
					Integer.valueOf(scheduleDate[2]));
			Calendar end = Calendar.getInstance();
			end.set(Integer.valueOf(scheduleEndDate[0]),
					Integer.valueOf(scheduleEndDate[1]),
					Integer.valueOf(scheduleEndDate[2]));
			int monthStart = (Integer.valueOf(scheduleDate[0]) - 1000) * 12
					+ start.get(Calendar.MONTH);
			int monthEnd = (Integer.valueOf(scheduleEndDate[0]) - 1000) * 12
					+ end.get(Calendar.MONTH);
			int months = monthEnd - monthStart;
			for (int i = 0; i <= months; i++) {
				if (i == 0) {
					cal.add(Calendar.MONTH, 0);
				} else {
					cal.add(Calendar.MONTH, 1);
				}
				handleDate(cal, scheduleID);
			}
		} else if (remindID == 7) {
			// 每年重复(从设置日程的这天(哪一年几月几号)，接下来的每年的这一天多要标记)
			for (int i = 0; i <= 2049 - Integer.parseInt(year); i++) {
				if (i == 0) {
					cal.add(Calendar.YEAR, 0);
				} else {
					cal.add(Calendar.YEAR, 1);
				}
				handleDate(cal, scheduleID);
			}
		}
		// 将标记日期存入数据库中
		if (null != operateType) {
			if ("add".equalsIgnoreCase(operateType)) {
				dao.saveTagDate(dateTagList);
			} else {
				dao.updateTagDate(dateTagList);
			}
		}

	}

	/**
	 * 日程标记日期的处理
	 * 
	 * @param cal
	 */
	public void handleDate(Calendar cal, int scheduleID) {
		ScheduleDateTag dateTag = new ScheduleDateTag();
		dateTag.setYear(cal.get(Calendar.YEAR));
		dateTag.setMonth(cal.get(Calendar.MONTH) + 1);
		dateTag.setDay(cal.get(Calendar.DATE));
		dateTag.setScheduleID(scheduleID);
		dateTagList.add(dateTag);
	}

	/**
	 * 通过选择提醒次数来处理最后的显示结果
	 * 
	 * @param year
	 * @param month
	 * @param day
	 * @param hour
	 * @param minute
	 * @param week
	 * @param remindID
	 */
	public String handleInfo(int year, int month, int day, int hour,
			int minute, String week, int remindID) {
		String remindType = remind[remindID]; // 提醒类型
		String show = "";
		if (0 <= remindID && remindID <= 4) {
			// 提醒一次,隔10分钟,隔30分钟,隔一小时
			show = year + "-" + month + "-" + day + "\t" + hour + ":" + minute
					+ "\t" + week + "\t\t" + remindType;
		} else if (remindID == 5) {
			// 每周
			show = "每周" + week + "\t" + hour + ":" + minute;
		} else if (remindID == 6) {
			// 每月
			show = "每月" + day + "号" + "\t" + hour + ":" + minute;
		} else if (remindID == 7) {
			// 每年
			show = "每年" + month + "-" + day + "\t" + hour + ":" + minute;
		}
		return show;
	}

	/**
	 * 点击item之后，显示的日期信息
	 * 
	 * @return
	 */
	public String getScheduleDate() {
		// Intent intent = getIntent();
		// // intent.getp
		// if(intent.getStringArrayListExtra("scheduleDate") != null){
		// //从CalendarActivity中传来的值（包含年与日信息）
		// scheduleDate = intent.getStringArrayListExtra("scheduleDate");
		// scheduleEndDate= intent.getStringArrayListExtra("scheduleDate");
		// }

		// int [] schType_remind = intent.getIntArrayExtra("schType_remind");
		// //从ScheduleTypeView中传来的值(包含日程类型和提醒次数信息)
		//
		// if(schType_remind != null){
		// sch_typeID = schType_remind[0];
		// remindID = schType_remind[1];
		// scheduleType.setText(sch_type[sch_typeID]+"\t\t\t\t"+remind[remindID]);
		// }
		// 得到年月日和星期
		scheduleYear = scheduleDate[0];
		scheduleMonth = scheduleDate[1];
		tempMonth = scheduleMonth;
		if (Integer.parseInt(scheduleMonth) < 10) {
			scheduleMonth = "0" + scheduleMonth;
		}
		scheduleDay = scheduleDate[2];
		tempDay = scheduleDay;
		if (Integer.parseInt(scheduleDay) < 10) {
			scheduleDay = "0" + scheduleDay;
		}
		week = scheduleDate[3];
		String hour_c = String.valueOf(hour);
		String minute_c = String.valueOf(minute);
		if (hour < 10) {
			hour_c = "0" + hour_c;
		}
		if (minute < 10) {
			minute_c = "0" + minute_c;
		}
		scheduleStartDateTxt = scheduleYear + "-" + scheduleMonth + "-"
				+ scheduleDay + " " + hour_c + ":" + minute_c;
		scheduleEndDateTxt = scheduleYear + "-" + scheduleMonth + "-"
				+ scheduleDay + " " + hour_c + ":" + minute_c;
		// 得到对应的阴历日期
		String scheduleLunarDay = getLunarDay(Integer.parseInt(scheduleYear),
				Integer.parseInt(scheduleMonth), Integer.parseInt(scheduleDay));
		String scheduleLunarMonth = lc.getLunarMonth(); // 得到阴历的月份
		StringBuffer scheduleDateStr = new StringBuffer();
		scheduleDateStr.append(scheduleYear).append("-").append(scheduleMonth)
				.append("-").append(scheduleDay).append(" ").append(hour_c)
				.append(":").append(minute_c).append("\n")
				.append(scheduleLunarMonth).append(scheduleLunarDay)
				.append(" ").append(week);
		// dateText.setText(scheduleDateStr);
		return scheduleDateStr.toString();
	}

	public String getScheduleStartDate() {
		String hour_c = String.valueOf(hour);
		String minute_c = String.valueOf(minute);
		if (hour < 10) {
			hour_c = "0" + hour_c;
		}
		if (minute < 10) {
			minute_c = "0" + minute_c;
		}
		// scheduleStartDateTxt=scheduleYear+"-"+scheduleMonth+"-"+scheduleDay+" "+hour_c+":"+minute_c;
		// 得到对应的阴历日期
		String scheduleLunarDay = getLunarDay(
				Integer.parseInt(scheduleDate[0]),
				Integer.parseInt(scheduleDate[1]),
				Integer.parseInt(scheduleDate[2]));
		String scheduleLunarMonth = lc.getLunarMonth(); // 得到阴历的月份
		StringBuffer scheduleDateStr = new StringBuffer();
		scheduleDateStr.append(scheduleDate[0]).append("-")
				.append(scheduleDate[1]).append("-").append(scheduleDate[2])
				.append(" ").append(hour_c).append(":").append(minute_c)
				.append("\n").append(scheduleLunarMonth)
				.append(scheduleLunarDay).append(" ").append(week);
		// dateText.setText(scheduleDateStr);
		return scheduleDateStr.toString();
	}

	public String getScheduleEndDate() {
		String hour_c = String.valueOf(hour);
		String minute_c = String.valueOf(minute);
		if (hour < 10) {
			hour_c = "0" + hour_c;
		}
		if (minute < 10) {
			minute_c = "0" + minute_c;
		}
		// scheduleEndDateTxt=scheduleYear+"-"+scheduleMonth+"-"+scheduleDay+" "+hour_c+":"+minute_c;
		// 得到对应的阴历日期
		String scheduleLunarDay = getLunarDay(
				Integer.parseInt(scheduleEndDate[0]),
				Integer.parseInt(scheduleEndDate[1]),
				Integer.parseInt(scheduleEndDate[2]));
		String scheduleLunarMonth = lc.getLunarMonth(); // 得到阴历的月份
		StringBuffer scheduleDateStr = new StringBuffer();
		scheduleDateStr.append(scheduleEndDate[0]).append("-")
				.append(scheduleEndDate[1]).append("-")
				.append(scheduleEndDate[2]).append(" ").append(hour_c)
				.append(":").append(minute_c).append("\n")
				.append(scheduleLunarMonth).append(scheduleLunarDay)
				.append(" ").append(week);
		// dateText.setText(scheduleDateStr);
		return scheduleDateStr.toString();
	}

	/**
	 * 根据日期的年月日返回阴历日期
	 * 
	 * @param year
	 * @param month
	 * @param day
	 * @return
	 */
	public String getLunarDay(int year, int month, int day) {
		String lunarDay = lc.getLunarDate(year, month, day, true);
		// {由于在取得阳历对应的阴历日期时，如果阳历日期对应的阴历日期为"初一"，就被设置成了月份(如:四月，五月。。。等)},所以在此就要判断得到的阴历日期是否为月份，如果是月份就设置为"初一"
		if (lunarDay.substring(1, 2).equals("月")) {
			lunarDay = "初一";
		}
		return lunarDay;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub

	}

	@Override
	protected int initLayout() {
		// TODO Auto-generated method stub
		return R.layout.schedule;
	}

	@Override
	protected View initCustomLayout() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected void initViewCmp() {
		// TODO Auto-generated method stub
		// scheduleTop = (BorderTextView) findViewById(R.id.scheduleTop);
		pDialog = new ProgressDialog(this);
		((TextView) findViewById(R.id.title_txt)).setText("编辑日程");
		Button back = (Button) findViewById(R.id.back);
		back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		scheduleType = (BorderTextView) findViewById(R.id.scheduleType);
		scheduleSave = (BorderTextView) findViewById(R.id.save);
		scheduleType.setBackgroundColor(Color.WHITE);
		scheduleType.setText(sch_type[0] + "\t\t\t\t" + remind[remindID]);
		dateText = (BorderTextView) findViewById(R.id.scheduleDate);
		endDateText = (BorderTextView) findViewById(R.id.scheduleEndDate);
		dateText.setBackgroundColor(Color.WHITE);
		endDateText.setBackgroundColor(Color.WHITE);
		scheduleText = (EditText) findViewById(R.id.scheduleText);
		scheduleTitle = (EditText) findViewById(R.id.scheduleTitle);
		scheduleText.setBackgroundColor(Color.WHITE);
		scheduleTitle.setBackgroundColor(Color.WHITE);
		scheduleObject = (BorderTextView) findViewById(R.id.scheduleObject);
		scheduleObject.setBackgroundColor(Color.WHITE);
		if (schText != null) {
			// 在选择日程类型之前已经输入了日程的信息，则在跳转到选择日程类型之前应当将日程信息保存到schText中，当返回时再次可以取得。
			scheduleText.setText(schText);
			// 一旦设置完成之后就应该将此静态变量设置为空，
			schText = "";
		}
		if (sch_typeID == 5) {
			scheduleObject.setVisibility(View.VISIBLE);
		} else {
			scheduleObject.setVisibility(View.GONE);
		}
		Date date = new Date();
		if (hour == -1 && minute == -1) {
			hour = date.getHours();
			minute = date.getMinutes();
		}

		Intent intent = getIntent();
		// intent.getp
		if (intent.getStringArrayListExtra("scheduleDate") != null) {
			// 从CalendarActivity中传来的值（包含年与日信息）
			List list = intent.getStringArrayListExtra("scheduleDate");
			for (int i = 0; i < list.size(); i++) {
				scheduleDate[i] = list.get(i).toString();
				scheduleEndDate[i] = list.get(i).toString();
			}

		}
		operateType = intent.getStringExtra("operateType");
		if (null != operateType) {
			if ("add".equalsIgnoreCase(operateType)) {
				if (intent.getStringExtra("objectID") != null) {
					// 从Contact中传来的值（包含年与日信息）
					scheduleObject.setVisibility(View.VISIBLE);
					scheduleObject.setText(String.valueOf(intent
							.getStringExtra("objectName")));
					selectObjectId = intent.getStringExtra("objectID");
					sch_typeID = 5;
					remindID = 0;
					scheduleType.setText(sch_type[sch_typeID] + "\t\t\t\t"
							+ remind[remindID]);
				}
				dateText.setText(getScheduleDate());
				endDateText.setText(getScheduleDate());
			} else {
				// edit修改的时候
				ScheduleVO scheduleVO = (ScheduleVO) intent
						.getSerializableExtra("schedule");
				SimpleDateFormat dateFormat = new SimpleDateFormat(
						"yyyy-MM-dd HH:mm");
				try {
					Date scheduleDateTemp = dateFormat.parse(scheduleVO
							.getScheduleStartDate());
					Date scheduleEndDateTemp = dateFormat.parse(scheduleVO
							.getScheduleEndDate());
					scheduleStartDateTxt = scheduleVO.getScheduleStartDate();
					scheduleEndDateTxt = scheduleVO.getScheduleEndDate();
					Calendar calendar = Calendar.getInstance();
					calendar.clear();
					calendar.setTime(scheduleDateTemp);
					scheduleDate[0] = String.valueOf(calendar
							.get(Calendar.YEAR));
					scheduleDate[1] = String.valueOf(calendar
							.get(Calendar.MONTH) + 1);
					scheduleDate[2] = String.valueOf(calendar
							.get(Calendar.DATE));
					scheduleDate[3] = getWeek(calendar
							.get(Calendar.DAY_OF_WEEK));
					scheduleYear = scheduleDate[0];
					scheduleMonth = scheduleDate[1];
					tempMonth = scheduleMonth;
					if (Integer.parseInt(scheduleMonth) < 10) {
						scheduleMonth = "0" + scheduleMonth;
					}
					scheduleDay = scheduleDate[2];
					tempDay = scheduleDay;
					if (Integer.parseInt(scheduleDay) < 10) {
						scheduleDay = "0" + scheduleDay;
					}
					week = scheduleDate[3];
					hour = calendar.get(Calendar.HOUR_OF_DAY);
					minute = calendar.get(Calendar.MINUTE);
					String hour_c = String.valueOf(hour);
					String minute_c = String.valueOf(minute);
					if (hour < 10) {
						hour_c = "0" + hour_c;
					}
					if (minute < 10) {
						minute_c = "0" + minute_c;
					}
					dateText.setText(getScheduleStartDate());
					calendar.clear();
					calendar.setTime(scheduleEndDateTemp);
					scheduleEndDate[0] = String.valueOf(calendar
							.get(Calendar.YEAR));
					scheduleEndDate[1] = String.valueOf(calendar
							.get(Calendar.MONTH) + 1);
					scheduleEndDate[2] = String.valueOf(calendar
							.get(Calendar.DATE));
					scheduleEndDate[3] = getWeek(calendar
							.get(Calendar.DAY_OF_WEEK));
					hour = calendar.get(Calendar.HOUR_OF_DAY);
					minute = calendar.get(Calendar.MINUTE);
					endDateText.setText(getScheduleEndDate());
					sch_typeID = scheduleVO.getScheduleTypeID(); // 日程类型
					remindID = scheduleVO.getRemindID(); // 提醒类型
					scheduleType.setText(sch_type[sch_typeID] + "\t\t\t\t"
							+ remind[remindID]);
					if (scheduleVO.getScheduleTypeID() == 5) {
						scheduleObject.setVisibility(View.VISIBLE);
					} else {
						scheduleObject.setVisibility(View.GONE);
					}
					scheduleTitle.setText(scheduleVO.getScheduleTitle());
					scheduleText.setText(scheduleVO.getScheduleContent());
				} catch (Exception e) {
					// TODO: handle exception
				}

			}
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (null != data) {
			Bundle b = data.getExtras();
			int[] arr = b.getIntArray("schType_remind");
			sch_typeID = arr[0];
			if (sch_typeID == 5) {
				scheduleObject.setVisibility(View.VISIBLE);
				scheduleText.setHint("请输入您的短信内容···");
			} else {
				scheduleObject.setVisibility(View.GONE);
				scheduleText.setHint("请输入您的日程内容···");
			}
			remindID = arr[1];
			scheduleType.setText(sch_type[sch_typeID] + "\t\t\t\t"
					+ remind[remindID]);
		}
	}

	@Override
	protected void initListener() {
		// TODO Auto-generated method stub
		// 获得日程类型
		scheduleType.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				schText = scheduleText.getText().toString();
				Intent intent = new Intent();
				intent.setClass(ScheduleView.this, ScheduleTypeView.class);
				intent.putExtra("sch_remind",
						new int[] { sch_typeID, remindID });
				// startActivity(intent);
				startActivityForResult(intent, 0);
			}
		});

		// 获得时间
		dateText.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (null == dateText.getText()
						|| ("").equals(dateText.getText())) {
					Calendar calendar = Calendar.getInstance();
					calendar.setTime(new Date());
					new DatePickerDialog(ScheduleView.this,
							new OnDateSetListener() {

								@Override
								public void onDateSet(DatePicker view,
										int year, int monthOfYear,
										int dayOfMonth) {
									// TODO Auto-generated method stub
									scheduleDate[0] = String.valueOf(year);
									if (monthOfYear + 1 < 10) {
										scheduleDate[1] = "0"
												+ String.valueOf(monthOfYear + 1);
									} else {
										scheduleDate[1] = String
												.valueOf(monthOfYear + 1);
									}
									if (dayOfMonth < 10) {
										scheduleDate[2] = "0"
												+ String.valueOf(dayOfMonth);
									} else {
										scheduleDate[2] = String
												.valueOf(dayOfMonth);
									}
									Calendar c = Calendar.getInstance();
									c.set(year, monthOfYear, dayOfMonth);
									scheduleDate[3] = String.valueOf(getWeek((c
											.get(Calendar.DAY_OF_WEEK))));
									scheduleYear = String.valueOf(year);
									scheduleMonth = String
											.valueOf(monthOfYear + 1);
									scheduleDay = String.valueOf(dayOfMonth);
									week = scheduleDate[3];
									// 临时日期时间变量，
									tempMonth = String.valueOf(monthOfYear + 1);
									tempDay = String.valueOf(dayOfMonth);
									TimePickerDialog t_start_dialog = new TimePickerDialog(
											ScheduleView.this,
											new OnTimeSetListener() {

												@Override
												public void onTimeSet(
														TimePicker view,
														int hourOfDay, int min) {
													time_picker_flag = false;
													hour = hourOfDay;
													minute = min;
													dateText.setText(getScheduleStartDate());
													scheduleStartDateTxt = scheduleDate[0]
															+ "-"
															+ scheduleDate[1]
															+ "-"
															+ scheduleDate[2]
															+ " "
															+ hourOfDay
															+ ":" + min;
												}
											}, hour, minute, true);
									if (!time_picker_flag) {
										t_start_dialog.show();
										time_picker_flag = true;
									}
								}
							}, Integer.valueOf(scheduleDate[0]), Integer
									.valueOf(scheduleDate[1]) - 1, Integer
									.valueOf(scheduleDate[2])).show();
				} else {
					new TimePickerDialog(ScheduleView.this,
							new OnTimeSetListener() {

								@Override
								public void onTimeSet(TimePicker view,
										int hourOfDay, int min) {
									if (Integer.valueOf(scheduleDate[1]) < 10) {
										scheduleDate[1] = "0"
												+ Integer.valueOf(
														scheduleDate[1])
														.toString();
									}
									if (Integer.valueOf(scheduleDate[2]) < 10) {
										scheduleDate[2] = "0"
												+ Integer.valueOf(
														scheduleDate[2])
														.toString();
									}
									hour = hourOfDay;
									minute = min;
									dateText.setText(getScheduleStartDate());
									scheduleStartDateTxt = scheduleDate[0]
											+ "-" + scheduleDate[1] + "-"
											+ scheduleDate[2] + " " + hourOfDay
											+ ":" + min;
								}
							}, hour, minute, true).show();
				}
			}
		});
		endDateText.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// if(null==endDateText.getText()||("").equals(endDateText.getText())){
				new DatePickerDialog(ScheduleView.this,
						new OnDateSetListener() {

							@Override
							public void onDateSet(DatePicker view, int year,
									int monthOfYear, int dayOfMonth) {
								// TODO Auto-generated method stub
								scheduleEndDate[0] = String.valueOf(year);
								if (monthOfYear + 1 < 10) {
									scheduleEndDate[1] = "0"
											+ String.valueOf(monthOfYear + 1);
								} else {
									scheduleEndDate[1] = String
											.valueOf(monthOfYear + 1);
								}
								if (dayOfMonth < 10) {
									scheduleEndDate[2] = "0"
											+ String.valueOf(dayOfMonth);
								} else {
									scheduleEndDate[2] = String
											.valueOf(dayOfMonth);
								}
								Calendar c = Calendar.getInstance();
								c.set(year, monthOfYear, dayOfMonth);
								scheduleEndDate[3] = String.valueOf(getWeek((c
										.get(Calendar.DAY_OF_WEEK))));
								TimePickerDialog t_end_dialog = new TimePickerDialog(
										ScheduleView.this,
										new OnTimeSetListener() {

											@Override
											public void onTimeSet(
													TimePicker view,
													int hourOfDay, int min) {
												time_picker_flag = false;
												hour = hourOfDay;
												minute = min;
												endDateText
														.setText(getScheduleEndDate());
												scheduleEndDateTxt = scheduleEndDate[0]
														+ "-"
														+ scheduleEndDate[1]
														+ "-"
														+ scheduleEndDate[2]
														+ " "
														+ hourOfDay
														+ ":"
														+ min;
											}
										}, hour, minute, true);
								if (!time_picker_flag) {
									t_end_dialog.show();
									time_picker_flag = true;
								}
							}
						}, Integer.valueOf(scheduleEndDate[0]), Integer
								.valueOf(scheduleEndDate[1]) - 1, Integer
								.valueOf(scheduleEndDate[2])).show();

				// }else{
				// new TimePickerDialog(ScheduleView.this, new
				// OnTimeSetListener() {
				//
				// @Override
				// public void onTimeSet(TimePicker view, int hourOfDay, int
				// min) {
				//
				// hour = hourOfDay;
				// minute = min;
				// endDateText.setText(getScheduleEndDate());
				// scheduleEndDateTxt=scheduleEndDate[0]+"-"+scheduleEndDate[1]+"-"+scheduleEndDate[2]+" "+hourOfDay+":"+min;
				// }
				// }, hour, minute, true).show();
				// }

			}
		});

		// 保存日程信息
		scheduleSave.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Date date = new Date();
				if (TextUtils.isEmpty(scheduleText.getText().toString())) {
					// 判断输入框是否为空
					new AlertDialog.Builder(ScheduleView.this)
							.setTitle("请输入日程标题").setMessage("日程标题不能为空")
							.setPositiveButton("确认", null).show();
				} else if (TextUtils
						.isEmpty(scheduleTitle.getText().toString())) {
					new AlertDialog.Builder(ScheduleView.this)
							.setTitle("请输入日程内容").setMessage("日程内容不能为空")
							.setPositiveButton("确认", null).show();
				} else if (date.after(formatStringToDate(scheduleEndDateTxt))) {
					new AlertDialog.Builder(ScheduleView.this)
							.setTitle("结束时间错误").setMessage("结束时间必须大于当前时间")
							.setPositiveButton("确认", null).show();
				} else {
					if (null != pDialog) {
						pDialog.setMessage("正在保存任务...");
						pDialog.setCanceledOnTouchOutside(false);
						pDialog.setCancelable(false);
						pDialog.show();
					} else {
						pDialog = new ProgressDialog(ScheduleView.this);
						pDialog.setCanceledOnTouchOutside(false);
						pDialog.setCancelable(false);
						pDialog.setMessage("正在保存任务...");
						pDialog.show();
					}
					new Thread(new Runnable() {

						@Override
						public void run() {
							// TODO Auto-generated method stub
							// 将日程信息保存
							String showDate = handleInfo(
									Integer.parseInt(scheduleYear),
									Integer.parseInt(tempMonth),
									Integer.parseInt(tempDay), hour, minute,
									week, remindID);
							ScheduleVO schedulevo = new ScheduleVO();
							if (null != operateType) {
								if ("add".equalsIgnoreCase(operateType)) {

								} else {
									ScheduleVO scheduleVO = (ScheduleVO) getIntent()
											.getSerializableExtra("schedule");
									schedulevo.setScheduleID(scheduleVO
											.getScheduleID());
								}
							}
							schedulevo.setScheduleTypeID(sch_typeID);
							schedulevo.setRemindID(remindID);
							schedulevo.setScheduleDate(showDate);
							schedulevo.setScheduleTitle(scheduleTitle.getText()
									.toString());
							// 0 为非周期任务 1为周期任务
							if (remindID == 0) {
								schedulevo.setScheduleType(0);
							} else {
								schedulevo.setScheduleType(1);
							}
							schedulevo.setScheduleContent(scheduleText
									.getText().toString());
							if (sch_typeID != 5) {
								schedulevo.setScheduleOpration("remind");
							} else {
								schedulevo.setScheduleOpration("sms");
							}
							// 单人任务、分类任务、群组任务从 getIntent中获取
							if (null != getIntent().getStringExtra(
									"scheduleMode")
									&& !"".equalsIgnoreCase(getIntent()
											.getStringExtra("scheduleMode"))) {
								schedulevo.setScheduleMode(getIntent()
										.getStringExtra("scheduleMode"));
							} else {
								if (null == selectMode) {
									schedulevo.setScheduleMode("0");
								} else {
									schedulevo.setScheduleMode(selectMode);
								}
							}
							if (scheduleObject.getVisibility() == View.VISIBLE) {
								if (null != getIntent().getStringExtra("from")) {
									if (getIntent().getStringExtra("from")
											.equalsIgnoreCase(
													"HomeContactActivity")) {
										schedulevo
												.setScheduleObjectID(selectObjectId);
									} else {
										schedulevo
												.setScheduleObjectID(selectObjectId);//
									}
								} else {
									schedulevo
											.setScheduleObjectID(selectObjectId);//
								}

							}

							switch (remindID) {
							case 0:
								schedulevo.setScheduleCycleType("1");
								break;
							case 1:
								schedulevo.setScheduleCycleType("10");
								break;
							case 2:
								schedulevo.setScheduleCycleType("30");
								break;
							case 3:
								schedulevo.setScheduleCycleType("60");
								break;
							case 4:
								schedulevo.setScheduleCycleType("D");
								break;
							case 5:
								schedulevo.setScheduleCycleType("W");
								break;
							case 6:
								schedulevo.setScheduleCycleType("M");
								break;
							case 7:
								schedulevo.setScheduleCycleType("Y");
								break;

							default:
								break;
							}
							schedulevo
									.setScheduleStartDate(scheduleStartDateTxt);
							schedulevo
									.setScheduleStartTime(scheduleStartDateTxt);
							schedulevo.setScheduleEndDate(scheduleEndDateTxt);
							schedulevo.setScheduleEndTime(scheduleEndDateTxt);
							int scheduleID = dao.saveOrUpdate(schedulevo);
							// 将scheduleID保存到数据中(因为在CalendarActivity中点击gridView中的一个Item可能会对应多个标记日程(scheduleID))
							String[] scheduleIDs = new String[] { String
									.valueOf(scheduleID) };
							// 设置日程标记日期(将所有日程标记日期封装到list中)
							setScheduleDateTag(remindID, scheduleYear,
									tempMonth, tempDay, scheduleID);
							dao.destoryDB();
							Intent i = getIntent();
							String from = i.getStringExtra("from");
							if (null == from) {
								Intent intent = new Intent();
								intent.setClass(ScheduleView.this,
										ScheduleInfoView.class);
								// intent.putExtra("scheduleID",
								// String.valueOf(scheduleID));
								// 保存时存入当前日期，以备列表显示
								ArrayList<String> list = new ArrayList<String>();
								for (int j = 0; j < scheduleDate.length; j++) {
									list.add(scheduleDate[j]);
								}
								intent.putStringArrayListExtra("scheduleDate",
										list);
								intent.putExtra("scheduleID", scheduleIDs);
								startActivity(intent);
							}
							if ("SearchActivity".equalsIgnoreCase(from)) {
								setResult(0);
							}
							if ("HomeContactActivity".equalsIgnoreCase(from)) {
								setResult(1000);
							}
							// dialog.dismiss();
							Message msg = new Message();
							Bundle bundle = new Bundle();
							bundle.putString("msg", "saveFinish");
							msg.setData(bundle);
							handler.sendMessage(msg);
						}

					}).start();
				}
			}
		});
		scheduleObject.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				selectMode = "0";
				LayoutInflater inflater = LayoutInflater
						.from(ScheduleView.this);
				LinearLayout root = new LinearLayout(ScheduleView.this);
				root.setOrientation(LinearLayout.VERTICAL);
				LayoutParams params = new LayoutParams(
						LayoutParams.WRAP_CONTENT, 200);
				root.setLayoutParams(params);
				inflater.inflate(R.layout.schedule_object_item, root);
				final Button sigle = (Button) root
						.findViewById(R.id.single_people);
				final Button type = (Button) root
						.findViewById(R.id.type_people);
				final Button group = (Button) root
						.findViewById(R.id.group_people);
				sigle.setBackgroundResource(R.drawable.home_btn_bg_s);
				type.setBackgroundResource(R.drawable.bg_sms_send_normal);
				group.setBackgroundResource(R.drawable.bg_sms_send_normal);
				datas = getAllContacts();
				for (int i = 0; i < datas.size(); i++) {
					list_object.add(datas.get(i)[1]);
				}
				adapter = new ArrayAdapter<String>(ScheduleView.this,
						R.layout.select_object_list_item, list_object);
				sigle.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						selectMode = "0";
						sigle.setBackgroundResource(R.drawable.home_btn_bg_s);
						type.setBackgroundResource(R.drawable.bg_sms_send_normal);
						group.setBackgroundResource(R.drawable.bg_sms_send_normal);
						datas.clear();
						datas = getAllContacts();
						list_object.clear();
						((BaseAdapter) adapter).notifyDataSetChanged();
						for (int i = 0; i < datas.size(); i++) {
							list_object.add(datas.get(i)[1]);
						}
						((BaseAdapter) adapter).notifyDataSetChanged();
					}
				});
				type.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						selectMode = "1";
						sigle.setBackgroundResource(R.drawable.bg_sms_send_normal);
						type.setBackgroundResource(R.drawable.home_btn_bg_s);
						group.setBackgroundResource(R.drawable.bg_sms_send_normal);
						datas.clear();
						datas = getAllTypesData();
						list_object.clear();
						((BaseAdapter) adapter).notifyDataSetChanged();
						for (int i = 0; i < datas.size(); i++) {
							list_object.add(datas.get(i)[1]);
						}
						((BaseAdapter) adapter).notifyDataSetChanged();
					}
				});
				group.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						selectMode = "2";
						sigle.setBackgroundResource(R.drawable.bg_sms_send_normal);
						type.setBackgroundResource(R.drawable.bg_sms_send_normal);
						group.setBackgroundResource(R.drawable.home_btn_bg_s);
						// TODO Auto-generated method stub
						datas.clear();
						datas = getAllGroupData();
						list_object.clear();
						((BaseAdapter) adapter).notifyDataSetChanged();
						for (int i = 0; i < datas.size(); i++) {
							list_object.add(datas.get(i)[1]);
						}
						((BaseAdapter) adapter).notifyDataSetChanged();
					}
				});
				final AlertDialog.Builder builder = new Builder(
						ScheduleView.this);
				builder.setTitle("请选择短信发送对象")
						.setView(root)
						.setAdapter(adapter,
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										// TODO Auto-generated method stub
										String[] str = datas.get(which);
										selectObjectId = str[0];
										scheduleObject.setText(str[1]);
									}
								}).show();
			}
		});
	}

	public List<String[]> getAllContacts() {
		DatabaseManager manager = new DatabaseManager(this);
		SQLiteDatabase sqlLite = manager.getWritableDatabase();
		List<String[]> list = new ArrayList<String[]>();
		Cursor cursor = sqlLite.query(DBInitScript.Table_ContactsInfo,
				new String[] { "contacts_id", "name" }, null, null, null, null,
				null, null);
		int count = cursor.getCount();
		if (count == 0) {
			return list;
		} else {
			list = new ArrayList<String[]>();
			for (int i = 0; i < count; i++) {
				cursor.moveToPosition(i);
				String[] str = new String[2];
				str[0] = String.valueOf(cursor.getInt(0));
				str[1] = String.valueOf(cursor.getString(1));
				list.add(str);
			}
		}
		cursor.close();
		sqlLite.close();
		return list;
	}
	
	public List<String[]> getAllGroupData() {
		DatabaseManager manager = new DatabaseManager(this);
		SQLiteDatabase sqlLite = manager.getWritableDatabase();
		List<String[]> list = new ArrayList<String[]>();
		Cursor cursor = sqlLite.query(DBInitScript.Table_GroupInfo,
				new String[] { "group_id", "group_name" }, null, null, null, null,
				null, null);
		int count = cursor.getCount();
		if (count == 0) {
			return list;
		} else {
			list = new ArrayList<String[]>();
			for (int i = 0; i < count; i++) {
				cursor.moveToPosition(i);
				String[] str = new String[2];
				str[0] = String.valueOf(cursor.getInt(0));
				str[1] = String.valueOf(cursor.getString(1));
				list.add(str);
			}
		}
		cursor.close();
		sqlLite.close();
		return list;
	}
	
	public List<String[]> getAllTypesData() {
		DatabaseManager manager = new DatabaseManager(this);
		SQLiteDatabase sqlLite = manager.getWritableDatabase();
		List<String[]> list = new ArrayList<String[]>();
		Cursor cursor = sqlLite.query(DBInitScript.Table_TypeInfo,
				new String[] { "type_id", "type_name" }, null, null, null, null,
				null, null);
		int count = cursor.getCount();
		if (count == 0) {
			return list;
		} else {
			list = new ArrayList<String[]>();
			for (int i = 0; i < count; i++) {
				cursor.moveToPosition(i);
				String[] str = new String[2];
				str[0] = String.valueOf(cursor.getInt(0));
				str[1] = String.valueOf(cursor.getString(1));
				list.add(str);
			}
		}
		cursor.close();
		sqlLite.close();
		return list;
	}

	private Date formatStringToDate(String str) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		try {
			return format.parse(str);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			return format.parse(format.format(new Date()));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return new Date();
	}

	@Override
	protected void initData() {
		// TODO Auto-generated method stub

	}

	@Override
	protected void initAsycnData() {
		// TODO Auto-generated method stub

	}

	@Override
	protected void changeDefaultSetting() {
		// TODO Auto-generated method stub

	}

	protected String getWeek(int i) {
		switch (i) {
		case 0:
			return "星期日";
		case 1:
			return "星期一";
		case 2:
			return "星期二";
		case 3:
			return "星期三";
		case 4:
			return "星期四";
		case 5:
			return "星期五";
		case 6:
			return "星期六";
		default:
			return "";
		}
	}
}
